package com.big.spike.config;

import com.big.sms.SmsFeignClient;
import com.big.spike.service.MerchandiseSpikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 监听失效的数据
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {


    @Autowired
    SmsFeignClient smsFeignClient;
    /**
     * 判断是否是数字
     * @param str
     * @return
     */
    public static boolean isNumeric4(String str) {
        return str != null && str.chars().allMatch(Character::isDigit);
    }

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Autowired
    MerchandiseSpikeService merchandiseSpikeService;
    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // message.toString()可以获取失效的key
        String expiredKey = message.toString();
        Integer flag=null;
        //提醒我
        if(isNumeric4(expiredKey)){
            smsFeignClient.remindMe(expiredKey);
        }else {
        String[] spike_start = expiredKey.split("_");
        if(spike_start[1].equals("start")||spike_start[1].equals("end")){
        if(spike_start[1].equals("start")){ //当前时间到准备开始时间计算
            flag=1;
        }
        if(spike_start[1].equals("end")){ //开始时间到结束时间计算
            flag=2;
        }
         merchandiseSpikeService.upSpike(Long.valueOf(spike_start[2]),flag);
        }
        }
        log.info("过期的key{}",expiredKey);
    }

}
